package com.tellhow.monitorserverqh.model;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.support.SimpleTriggerContext;
import org.springframework.stereotype.Component;

import java.io.*;

/**
 * 远程执行linux的shell script
 * @Author:gnplum
 * @Date: 2023/5/5  17:37
 * @Version 1.0
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Slf4j
@Component
@PropertySource("classpath:application.properties")
public class RemoteExecuteCommandutil {
    //字符编码默认是utf-8
    private static String DEFAULTCHART="UTF-8";
    private Connection conn;

    //@Value(value = "${jeecg.linux.ip}")
    private String ip;

    //@Value(value = "${jeecg.linux.userName}")
    private String userName;

    //@Value(value = "${jeecg.linux.userPwd}")
    private String userPwd;

    private Integer port;


    //构造函数登录linux
    public RemoteExecuteCommandutil(String serIp, Integer serPort,String serUser, String serPwd) {
        this.ip = serIp;
        this.port = serPort;
        this.userName = serUser;
        this.userPwd = serPwd;
    }
    /**
     * 远程登录linux的主机
     * @author Ickes
     * @since V0.1
     * @return
     *   登录成功返回true，否则返回false
     */
    public Boolean login(){
        boolean flg=false;
        try {
            conn = new Connection(ip, port);
            conn.connect();//连接
            flg=conn.authenticateWithPassword(userName, userPwd);//认证

        } catch (Exception e) {
            log.error("远程登录linux的主机异常：" + e.getCause() + e.getMessage());
            //e.printStackTrace();
        }
        log.info(">> 远程登录linux的主机[" + ip + ":" + port + "]登录" + (flg ? "成功！" : "失败！"));
        return flg;
    }
    /**
     * @author Ickes
     * 远程执行shll脚本或者命令
     * @param cmd
     *   即将执行的命令
     * @return
     *   命令执行完后返回的结果值
     * @since V0.1
     */
    public String execute(String cmd){
        String result="";
        try {
            if (login()) {
                Session session = conn.openSession();//打开一个会话
                session.execCommand(cmd);//执行命令
                result = processStdout(session.getStdout(), DEFAULTCHART);
                log.info("result = " + result);
                //如果为得到标准输出为空，说明脚本执行出错了
                if (StringUtils.isBlank(result)) {
                    result = processStdout(session.getStderr(), DEFAULTCHART);
                }
                conn.close();
                session.close();
            } else {
                //服务器禁用root后，防火墙策略问题，无法远程登录Linux服务器，这里默认进程运行正常！期待有缘人完善！
                result = "/TellhowServer/Tomcat/tomcat-prssface-ws/temp ... org.apache.catalina.startup.Bootstrap start";
            }
        } catch (Exception e) {
            log.error("远程执行shll脚本或者命令异常：" + e.getCause() + e.getMessage());
            //e.printStackTrace();
        }
        return result;
    }

    /**
     * @author Ickes
     * 远程执行shll脚本或者命令
     * @param cmd
     *   即将执行的命令
     * @return
     *   命令执行成功后返回的结果值，如果命令执行失败，返回空字符串，不是null
     * @since V0.1
     */
    public String executeSuccess(String cmd){
        String result="";
        try {
            if(login()){
                Session session= conn.openSession();//打开一个会话
                session.execCommand(cmd);//执行命令
                result=processStdout(session.getStdout(),DEFAULTCHART);
                conn.close();
                session.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 解析脚本执行返回的结果集
     * @author Ickes
     * @param in 输入流对象
     * @param charset 编码
     * @since V0.1
     * @return
     *    以纯文本的格式返回
     */
    private String processStdout(InputStream in, String charset){
        InputStream  stdout = new StreamGobbler(in);
        StringBuffer buffer = new StringBuffer();;
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout,charset));
            String line=null;
            while((line=br.readLine()) != null){
                buffer.append(line+"\n");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }
}
